#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dlx_solver.h"
#include "baseobject.h"
#include "generator.h"

#define  _CRT_SECURE_NO_WARNINGS

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
	ui->setupUi(this);
    QPoint topleft(0,ui->menuBar->height());
    int boxwidth=80;

    for(int x=1;x<=9;++x)
    {
        QPushButton *box=new QPushButton(this);
        //box->setFrameShape(QFrame::Box);
        box->setGeometry(topleft.x()+( (x-1)%3 * boxwidth),topleft.y()+( (x-1)/3 * boxwidth),boxwidth,boxwidth);
        boxs.push_back(box);
    }
    int cellwidth=26;

    int fontsize=18;
    while(true)
    {
        QFont tmp("Arial",fontsize);
        tmp.setPointSize(fontsize);
        QFontMetricsF fm(tmp);
        qreal pixelsWide = fm.width("8");
        qreal pixelsHigh = fm.height();
        if(pixelsWide>=cellwidth || pixelsHigh >= cellwidth)
            break;
        ++fontsize;
    }
    QFont font("Arial",fontsize);

    for(int x=1;x<=9;++x)
    {
        for(int y=1;y<=9;++y)
        {
            QPushButton *cell=new QPushButton(this);
            int xshift=(x-1)/3*2+1;
            int yshift=(y-1)/3*2+1;
            //cell->setFrameShape(QFrame::Box);
			//cell->setObjectName("CellButton");
			qDebug("%s\n",qPrintable(cell->objectName()));
            cell->setGeometry(topleft.x()+ (x-1)*cellwidth+xshift, topleft.y()+(y-1)*cellwidth+yshift, cellwidth, cellwidth);
            cell->setText(QString::number(x));
            cell->setFont(font);
            cells.push_back(cell);
			connect(cell,SIGNAL(clicked(bool)),this,SLOT(on_CellButton_clicked(bool)));
        }
	}
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_btnTest_clicked(bool bVal)
{
	qDebug("btnTest is clicked!%d\n",bVal);
}


void MainWindow::on_CellButton_clicked(bool bVal)
{
	QObject *obj=sender();
	qDebug("CellButton is clicked by %s!%d\n",qPrintable(obj->objectName()),bVal);

	generator gen;
	string strSudoku=gen.do_dlx_generator();
	const char *p=strSudoku.c_str();

	Puzzle pz;
	pz.loadPuzzle(p);

	const char *outp=pz.exportPuzzle();

        qDebug()<<outp;
}
